home *** CD-ROM | disk | FTP | other *** search
/ Chip 1998 September / CHIP Eylül 1998.iso / Slackwar / docs / mini / Ext2fs-Undeletion < prev    next >
Text File  |  1997-08-07  |  40KB  |  888 lines

  1.   Linux Ext2fs Undeletion mini-HOWTO
  2.   Aaron Crane, <aaronc@pobox.com>
  3.   v1.2, 4 August 1997
  4.  
  5.   Picture this.  You've spent the last three days with no sleep, no
  6.   food, not even a shower.  Your hacking compulsion has at last paid
  7.   off: you've finished that program that will bring you world-wide fame
  8.   and recognition.  All that you still need to do is tar it up and put
  9.   it on Sunsite.  Oh, and delete all those Emacs backup files.  So you
  10.   say rm * ~.  And too late, you notice the extra space in that command.
  11.   You've just deleted your magnum opus!  But help is at hand.  This doc¡
  12.   ument presents a discussion of how to retrieve deleted files from a
  13.   Second Extended File System.  Just maybe, you'll be able to release
  14.   that program after all...
  15.  
  16.   1.  Introduction
  17.  
  18.   This mini-Howto attempts to provide hints on how to retrieve deleted
  19.   files from an ext2 filesystem.  It also contains a limited amount of
  20.   discussion of how to avoid deleting files in the first place.
  21.  
  22.   I intend it to be useful certainly for people who have just had, shall
  23.   we say, a little accident with rm; however, I also hope that people
  24.   read it anyway.  You never know: one day, some of the information in
  25.   here could save your bacon.
  26.  
  27.   The text assumes a little background knowledge about UNIX filesystems
  28.   in general; however, I hope that it will be accessible to most Linux
  29.   users.  If you are an outright beginner, I'm afraid that undeleting
  30.   files under Linux does require a certain amount of technical knowledge
  31.   and persistence, at least for the time being.
  32.  
  33.   You will be unable to recover deleted files from an ext2 filesystem
  34.   without at least read access to the raw device on which the file was
  35.   stored.  In general, this means that you must be root.  You also need
  36.   debugfs from the e2fsprogs package.  This should have been installed
  37.   by your distribution.
  38.  
  39.   Why have I written this?  It stems largely from my own experiences
  40.   with a particularly foolish and disastrous rm -r command as root.  I
  41.   deleted about 97 JPEG files which I needed and could almost certainly
  42.   not recover from other sources.  Using some helpful tips (see section
  43.   ``Credits and Bibliography'') and a great deal of persistence, I
  44.   recovered 91 files undamaged.  I managed to retrieve at least parts of
  45.   five of the rest (enough to see what the picture was in each case).
  46.   Only one was undisplayable, and even for this one, I am fairly sure
  47.   that no more than 1024 bytes were lost (though unfortunately from the
  48.   beginning of the file; given that I know nothing about the JFIF file
  49.   format I had done as much as I could).
  50.  
  51.   I shall discuss further below what sort of recovery rate you can
  52.   expect for deleted files.
  53.  
  54.   1.1.  Revision history
  55.  
  56.   The various publicly-released revisions of this document (and their
  57.   publication dates) are as follows:
  58.  
  59.   ╖  v1.0 on 18 January 1997
  60.  
  61.   ╖  v1.1 on 23 July 1997 (see section ``Changes in v1.1'')
  62.  
  63.   ╖  v1.2 on 4 August 1997 (see section ``Changes in v1.2'')
  64.  
  65.   1.1.1.  Changes in version 1.1
  66.  
  67.   What changes have been made in this version?  First of all, the thinko
  68.   in the example of file recovery has been fixed.  Thankyou to all those
  69.   who wrote to point out my mistaek; I hope I've learned to be more
  70.   careful when making up program interaction.
  71.  
  72.   Secondly, the discussion of UNIX filesystem layout has been rewritten
  73.   to be, I hope, more understandable.  I wasn't entirely happy with it
  74.   in the first place, and some people's comments indicated that it
  75.   wasn't clear.
  76.  
  77.   Thirdly, the vast uuencoded gzipped tarball of fsgrab in the middle of
  78.   the file has been removed.  The program is now available on my website
  79.   <http://pobox.com/~aaronc/tech/fsgrab-1.0.tar.gz> and it should soon
  80.   make its way onto Sunsite
  81.   <http://sunsite.unc.edu/pub/Linux/utils/disk-management/> (and
  82.   mirrors).
  83.  
  84.   Fourthly, the document has been translated into the Linux
  85.   Documentation Project SGML Tools content markup language.  This markup
  86.   language can be easily converted to any of a number of other markup
  87.   languages (including HTML and LaTeX) for convenient display and
  88.   printing.  One benefit of this is that beautiful typography in paper
  89.   editions is a much more achievable goal; another is that the document
  90.   has cross-references and hyperlinks when viewed on the Web.
  91.  
  92.   1.1.2.  Changes in v1.2
  93.  
  94.   This revision is very much an incremental change.  It's here mainly to
  95.   include changes suggested by readers, one of which is particularly
  96.   important.
  97.  
  98.   The first change was suggested by Egil Kvaleberg <egil@kvaleberg.no>,
  99.   who pointed out the dump command in debugfs.  Thanks again, Egil.
  100.  
  101.   The second change is to mention the use of chattr for avoiding
  102.   deleting important files.  Thanks to Herman Suijs <H.P.M.Suijs@kub.nl>
  103.   for mentioning this one.
  104.  
  105.   The abstract has been revised.  URLs have been added for organisations
  106.   and software.  Various other minor changes have been made (including
  107.   fixing typos and so on).
  108.  
  109.   1.2.  Canonical locations of this document
  110.  
  111.   The latest public release of this document should always be available
  112.   in plain text format on the Linux Documentation Project site
  113.   <http://sunsite.unc.edu/LDP/> (and mirrors).
  114.  
  115.   The latest release is also kept on my website
  116.   <http://pobox.com/~aaronc/> in several formats:
  117.  
  118.   ╖  SGML source <http://pobox.com/~aaronc/tech/e2-undel/howto.sgml>.
  119.      This is the source as I have written it, using the SGML Tools
  120.      package.
  121.  
  122.   ╖  HTML <http://pobox.com/~aaronc/tech/e2-undel/html/>.  This is HTML,
  123.      automatically generated from the SGML source.
  124.  
  125.   ╖  Plain text <http://pobox.com/~aaronc/tech/e2-undel/howto.txt>.
  126.      This is plain text, which is also automatically generated from the
  127.      SGML source.  Note that this file is identical to the one on
  128.      Sunsite, so if you want the plain text, you are recommended to get
  129.      it from your favourite LDP mirror (as it will probably be much
  130.      faster).
  131.  
  132.   2.  How not to delete files
  133.  
  134.   It is vital to remember that Linux is unlike MS-DOS when it comes to
  135.   undeletion.  For MS-DOS (and its bastard progeny Windows 95), it is
  136.   generally fairly straightforward to undelete a file - the `operating
  137.   system' (I use the term loosely) even comes with a utility which
  138.   automates much of the process.  For Linux, this is not the case.
  139.  
  140.   So.  Rule number one (the prime directive, if you will) is:
  141.  
  142.        KEEP BACKUPS
  143.  
  144.   no matter what.  I know, I'm a fine one to talk.  I shall merely plead
  145.   impoverishment (being a student must have some perks) and exhort all
  146.   right-thinking Linux users to go out and buy a useful backup device,
  147.   work out a decent backup schedule, and to stick to it.  For more
  148.   information on this, read Frisch (1995) (see section ``Bibliography
  149.   and Credits'').
  150.  
  151.   In the absence of backups, what then?  (Or even in the presence of
  152.   backups: belt and braces is no bad policy where important data is
  153.   concerned.)
  154.  
  155.   Try to set the permissions for important files to 440 (or less):
  156.   denying yourself write access to them means that rm requires an
  157.   explicit confirmation before deleting.  (I find, however, that if I'm
  158.   recursively deleting a directory with rm -r, I'll interrupt the
  159.   program on the first or second confirmation request and reissue the
  160.   command as rm -rf.)
  161.  
  162.   A good trick for selected files is to create a hard link to them in a
  163.   hidden directory.  I heard a story once about a sysadmin who
  164.   repeatedly deleted /etc/passwd by accident (thereby half-destroying
  165.   the system).  One of the fixes for this was to do something like the
  166.   following (as root):
  167.  
  168.        # mkdir /.backup
  169.        # ln /etc/passwd /.backup
  170.  
  171.   It requires quite some effort to delete the file contents completely:
  172.   if you say
  173.  
  174.        # rm /etc/passwd
  175.  
  176.   then
  177.  
  178.   # ln /.backup/passwd /etc
  179.  
  180.   will retrieve it.  Of course, this does not help in the event that you
  181.   overwrite the file, so keep backups anyway.
  182.  
  183.   On an ext2 filesystem, it is possible to use ext2 attributes to
  184.   protect things.  These attributes are manipulated with the chattr
  185.   command.  There is an `append-only' attribute: a file with this
  186.   attribute may be appended to, but may not be deleted, and the existing
  187.   contents of the file may not be overwritten.  If a directory has this
  188.   attribute, any files or directories within it may be modified as
  189.   normal, but no files may be deleted.  The `append-only' attribute is
  190.   set with
  191.  
  192.        $ chattr +a FILE...
  193.  
  194.   There is also an `immutable' attribute, which can only be set or
  195.   cleared by root.  A file or directory with this attribute may not be
  196.   modified, deleted, renamed, or (hard) linked.  It may be set as
  197.   follows:
  198.  
  199.        # chattr +i FILE...
  200.  
  201.   The ext2fs also provides the `undeletable' attribute (+u in chattr).
  202.   The intention is that if a file with that attribute is deleted,
  203.   instead of actually being reused, it is merely moved to a `safe
  204.   location' for deletion at a later date.  Unfortunately this feature
  205.   has not yet been implemented in mainstream kernels.  However, various
  206.   kernel patches exist which provide the ability to do reversible
  207.   deletion; see <http://www.linuxhq.com/> if you're interested in
  208.   patching this facility into your kernel.  The most recent patch I know
  209.   of is by Rogier Wolff <R.E.Wolff@BitWizard.nl>, Darren J Moffat
  210.   <darren@xarius.demon.co.uk> and Kurt Huwig <kurt@huwig.de>.  I would
  211.   point out though that while this patch implements the feature, it is
  212.   not an `undeletion solution' at the moment.  Undeletable files are
  213.   merely moved into another directory; there should be a daemon to
  214.   periodically clean up that directory.
  215.  
  216.   Some people advocate making rm a shell alias or function for rm -i
  217.   (which asks for confirmation on every file you delete).  Indeed,
  218.   recent versions of the Red Hat distribution <http://www.redhat.com/>
  219.   do this by default for all users, including root.  Personally, I
  220.   cannot stand software which won't run unattended, so I don't do that.
  221.   There is also the problem that sooner or later, you'll be running in
  222.   single-user mode, or using a different shell, or even a different
  223.   machine, where your rm function doesn't exist.  If you expect to be
  224.   asked for confirmation, it is easy to forget where you are and to
  225.   specify too many files for deletion.  Likewise, the various scripts
  226.   and programs that replace rm are, IMHO, very dangerous.
  227.  
  228.   A slightly better solution is to start using a package which handles
  229.   `recyclable' deletion by providing a command not named rm.  For
  230.   details on these, see Peek, et al (1993) (see section ``Bibliography
  231.   and Credits'').
  232.  
  233.   3.  What recovery rate can I expect?
  234.  
  235.   That depends.  Among the problems with recovering files on a high-
  236.   quality, multi-tasking, multi-user operating system like Linux is that
  237.   you never know when someone wants to write to the disk.  So when the
  238.   operating system is told to delete a file, it assumes that the blocks
  239.   used by that file are fair game when it wants to allocate space for a
  240.   new file.  (This is a specific example of a general principle for
  241.   Linux: the kernel and the associated tools assume that the users
  242.   aren't idiots.)  In general, the more usage your machine gets, the
  243.   less likely you are to be able to recover files successfully.
  244.  
  245.   Also, disk fragmentation can affect the ease of recovering files.  If
  246.   the partition containing the deleted files is very fragmented, you are
  247.   unlikely to be able to read a whole file.
  248.  
  249.   If your machine, like mine, is effectively a single-user workstation
  250.   (mine doesn't even have a net connection yet; maybe next year), and
  251.   you weren't doing anything disk-intensive at the fatal moment of
  252.   deleting those files, I would expect a recovery rate in the same ball-
  253.   park as detailed above.  I retrieved nearly 94% of the files (and
  254.   these were binary files, please note) undamaged.  If you get 80% or
  255.   better, you can feel pretty pleased with yourself, I should think.
  256.  
  257.   4.  So, how do I undelete a file?
  258.  
  259.   The procedure principally involves finding the data on the raw
  260.   partition device and making it visible again to the operating system.
  261.   There are basically two ways of doing this: one is to modify the
  262.   existing filesystem such that the deleted inodes have their `deleted'
  263.   flag removed, and hope that the data just magically falls back into
  264.   place.  The other method, which is safer but slower, is to work out
  265.   where the data lies in the partition and write it out into a new file.
  266.  
  267.   There are some steps you need to take before beginning to attempt your
  268.   data recovery; see sections ``Unmounting the filesystem'', ``Preparing
  269.   to change inodes directly'' and ``Preparing to write data elsewhere''
  270.   for details.  To find out how to actually retrieve your files, see
  271.   sections ``Finding the deleted inodes'', ``Obtaining the details of
  272.   the inodes'', ``Recovering data blocks'' and ``Modifying inodes
  273.   directly''.
  274.  
  275.   5.  Unmounting the filesystem
  276.  
  277.   Regardless of which method you choose, the first step is to unmount
  278.   the filesystem containing the deleted files.  I strongly discourage
  279.   any urges you may have to mess around on a mounted filesystem.  This
  280.   step should be performed as soon as possible after you realise that
  281.   the files have been deleted.
  282.  
  283.   The simplest method is as follows: assuming the deleted files were in
  284.   the /usr partition, say:
  285.  
  286.        # umount /usr
  287.  
  288.   You may, however, want to keep some things in /usr available.  So
  289.   remount it read-only:
  290.  
  291.        # mount -o ro,remount /usr
  292.  
  293.   If the deleted files were on the root partition, you'll need to add a
  294.   -n option to prevent mount from trying to write to /etc/mtab:
  295.  
  296.        # mount -n -o ro,remount /
  297.  
  298.   Regardless of all this, it is possible that there will be another
  299.   process using that filesystem (which will cause the unmount to fail
  300.   with an error such as `Resource busy').  There is a program which will
  301.   send a signal to any process using a given file or mount point: fuser.
  302.   Try this for the /usr partition:
  303.  
  304.        # fuser -v -m /usr
  305.  
  306.   This lists the processes involved.  Assuming none of them are vital,
  307.   you can say
  308.  
  309.        # fuser -k -v -m /usr
  310.  
  311.   to send each process a SIGKILL (which is guaranteed to kill it), or
  312.   for example,
  313.  
  314.        # fuser -k -TERM -v -m /usr
  315.  
  316.   to give each one a SIGTERM (which will normally make the process exit
  317.   cleanly).
  318.  
  319.   6.  Preparing to change inodes directly
  320.  
  321.   My advice?  Don't do it this way.  I really don't think it's wise to
  322.   play with a filesystem at a low enough level for this to work.  There
  323.   are also has problems in that you can only reliably recover the first
  324.   12 blocks of each file.  So if you have any long files to recover,
  325.   you'll have to use the other method anyway.  (Although see section
  326.   ``Will this get easier in future?'' for additional information.)
  327.  
  328.   If you feel you must do it this way, my advice is to copy the raw
  329.   partition data to an image on a different partition, and then mount
  330.   this using loopback:
  331.  
  332.        # cp /dev/hda5 /root/working
  333.        # mount -t ext2 -o loop /root/working /mnt
  334.  
  335.   This does, however, require a recent version of mount.  (Although you
  336.   should get version 2.6 or newer anyway, as all earlier versions have a
  337.   major security bug which allows peons to get root access.  The major
  338.   distributions, that is, Debian, RedHat and Slackware, have all been
  339.   updated with version 2.6 of mount.)
  340.  
  341.   Using loopback means that when you completely destroy the filesystem
  342.   (as you quite possibly will), all you have to do is copy the raw
  343.   partition back and start again.
  344.  
  345.   7.  Preparing to write data elsewhere
  346.  
  347.   You need to make sure you have a rescue partition somewhere.
  348.   Hopefully, your system has several partitions on it: perhaps a root, a
  349.   /usr, and a /home.  With all these to choose from, you should have no
  350.   problem: just create a new directory on one of these.
  351.  
  352.   If you have only a root partition, and store everything on that (like
  353.   me, until I can get around to repartitioning), things are slightly
  354.   more awkward.  Perhaps you have an MS-DOS or Windows partition you
  355.   could use?  Or you have the ramdisk driver in your kernel, maybe as a
  356.   module?  To use the ramdisk (assuming a kernel more recent than
  357.   1.3.48), say the following:
  358.  
  359.        # dd if=/dev/zero of=/dev/ram0 bs=1k count=2048
  360.        # mke2fs -v -m 0 /dev/ram0 2048
  361.        # mount -t ext2 /dev/ram0 /mnt
  362.  
  363.   This creates a 2MB ramdisk volume, and mounts it on /mnt.
  364.  
  365.   A short word of warning: if you use kerneld to automatically load and
  366.   unload kernel modules, then don't unmount the ramdisk until you've
  367.   copied any files from it onto non-volatile storage.  Once you unmount
  368.   it, kerneld assumes it can unload the module (after the usual waiting
  369.   period), and once this happens, the memory gets re-used by other parts
  370.   of the kernel, losing all the painstaking hours you just spent
  371.   recovering your data.
  372.  
  373.   If you have any of the new `superfloppy' removable devices, they're
  374.   probably a good choice for a rescue partition location.  Otherwise,
  375.   you'll just have to stick with floppies.
  376.  
  377.   The other thing you're likely to need is a program which can read the
  378.   necessary data from the middle of the partition device.  At a pinch,
  379.   dd will do the job, but to read from, say, 600 MB into an 800 MB
  380.   partition, dd insists on reading but ignoring the first 600 MB.  This
  381.   takes a not inconsiderable amount of time.  My way round this was to
  382.   write a program which will seek to the middle of the partition.  It's
  383.   called fsgrab; you can find the source package on my website
  384.   <http://pobox.com/~aaronc/tech/fsgrab-1.0.tar.gz> and it should soon
  385.   make its way onto Sunsite
  386.   <http://sunsite.unc.edu/pub/Linux/utils/disk-management/> (and
  387.   mirrors).  If you want to use this method, the rest of this mini-Howto
  388.   assumes that you have fsgrab.
  389.  
  390.   If none of the files you are trying to recover were more than 12
  391.   blocks long (where a block is usually one kilobyte), then you won't
  392.   need fsgrab.
  393.  
  394.   If you need to use fsgrab but don't want to, it is fairly
  395.   straightforward to translate an fsgrab command-line to one for dd.  If
  396.   we have
  397.  
  398.        fsgrab -c count -s skip device
  399.  
  400.   then the corresponding dd command is
  401.  
  402.        dd bs=1k if=device count=count skip=skip
  403.  
  404.   I must warn you that, although fsgrab functioned perfectly for me, I
  405.   can take no responsibility for how it performs.  It was really a very
  406.   quick and dirty kludge just to get things to work.  For more details
  407.   on the lack of warranty, see the `No Warranty' section in the COPYING
  408.   file included with it (the GNU General Public Licence).
  409.  
  410.   8.  Finding the deleted inodes
  411.  
  412.   The next step is to ask the filesystem which inodes have recently been
  413.   freed.  This is a task you can accomplish with debugfs.  Start debugfs
  414.   with the name of the device on which the filesystem is stored:
  415.  
  416.        # debugfs /dev/hda5
  417.  
  418.   If you want to modify the inodes directly, add a -w option to enable
  419.   writing to the filesystem:
  420.  
  421.        # debugfs -w /dev/hda5
  422.  
  423.   The debugfs command to find the deleted inodes is lsdel.  So, type the
  424.   command at the prompt:
  425.  
  426.        debugfs:  lsdel
  427.  
  428.   After much wailing and grinding of disk mechanisms, a long list is
  429.   piped into your favourite pager (the value of $PAGER).  Now you'll
  430.   want to save a copy of this somewhere else.  If you have less, you can
  431.   type -o followed by the name of an output file.  Otherwise, you'll
  432.   have to arrange to send the output elsewhere.  Try this:
  433.  
  434.        debugfs:  quit
  435.        # echo lsdel | debugfs /dev/hda5 > lsdel.out
  436.  
  437.   Now, based only on the deletion time, the size, the type, and the
  438.   numerical permissions and owner, you must work out which of these
  439.   deleted inodes are the ones you want.  With luck, you'll be able to
  440.   spot them because they're the big bunch you deleted about five minutes
  441.   ago.  Otherwise, trawl through that list carefully.
  442.  
  443.   I suggest that if possible, you print out the list of the inodes you
  444.   want to recover.  It will make life a lot easier.
  445.  
  446.   9.  Obtaining the details of the inodes
  447.  
  448.   debugfs has a stat command which prints details about an inode.  Issue
  449.   the command for each inode in your recovery list.  For example, if
  450.   you're interested in inode number 148003, try this:
  451.  
  452.        debugfs:  stat <148003>
  453.        Inode: 148003   Type: regular    Mode:  0644   Flags: 0x0   Version: 1
  454.        User:   503   Group:   100   Size: 6065
  455.        File ACL: 0    Directory ACL: 0
  456.        Links: 0   Blockcount: 12
  457.        Fragment:  Address: 0    Number: 0    Size: 0
  458.        ctime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  459.        atime: 0x31a21dd1 -- Tue May 21 20:47:29 1996
  460.        mtime: 0x313bf4d7 -- Tue Mar  5 08:01:27 1996
  461.        dtime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  462.        BLOCKS:
  463.        594810 594811 594814 594815 594816 594817
  464.        TOTAL: 6
  465.  
  466.   If you have a lot of files to recover, you'll want to automate this.
  467.   Assuming that your lsdel list of inodes to recover in is in lsdel.out,
  468.   try this:
  469.  
  470.        # cut -c1-6 lsdel.out | grep "[0-9]" | tr -d " " > inodes
  471.  
  472.   This new file inodes contains just the numbers of the inodes to
  473.   recover, one per line.  We save it because it will very likely come in
  474.   handy later on.  Then you just say:
  475.  
  476.   # sed 's/^.*$/stat <\0>/' inodes | debugfs /dev/hda5 > stats
  477.  
  478.   and stats contains the output of all the stat commands.
  479.  
  480.   10.  Recovering data blocks
  481.  
  482.   This part is either very easy or distinctly less so, depending on
  483.   whether the file you are trying to recover is more than 12 blocks
  484.   long.
  485.  
  486.   10.1.  Short files
  487.  
  488.   If the file was no more than 12 blocks long, then the block numbers of
  489.   all its data are stored in the inode: you can read them directly out
  490.   of the stat output for the inode.  Moreover, debugfs has a command
  491.   which performs this task automatically.  To take the example we had
  492.   before, repeated here:
  493.  
  494.        debugfs:  stat <148003>
  495.        Inode: 148003   Type: regular    Mode:  0644   Flags: 0x0   Version: 1
  496.        User:   503   Group:   100   Size: 6065
  497.        File ACL: 0    Directory ACL: 0
  498.        Links: 0   Blockcount: 12
  499.        Fragment:  Address: 0    Number: 0    Size: 0
  500.        ctime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  501.        atime: 0x31a21dd1 -- Tue May 21 20:47:29 1996
  502.        mtime: 0x313bf4d7 -- Tue Mar  5 08:01:27 1996
  503.        dtime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  504.        BLOCKS:
  505.        594810 594811 594814 594815 594816 594817
  506.        TOTAL: 6
  507.  
  508.   This file has six blocks.  Since this is less than the limit of 12, we
  509.   get debugfs to write the file into a new location, such as
  510.   /mnt/recovered.000:
  511.  
  512.        debugfs:  dump <148003> /mnt/recovered.000
  513.  
  514.   Of course, this can also be done with fsgrab; I'll present it here as
  515.   an example of using it:
  516.  
  517.        # fsgrab -c 2 -s 594810 /dev/hda5 > /mnt/recovered.000
  518.        # fsgrab -c 4 -s 594814 /dev/hda5 >> /mnt/recovered.000
  519.  
  520.   With either debugfs or fsgrab, there will be some garbage at the end
  521.   of /mnt/recovered.000, but that's fairly unimportant.  If you want to
  522.   get rid of it, the simplest method is to take the Size field from the
  523.   inode, and plug it into the bs option in a dd command line:
  524.  
  525.        # dd count=1 if=/mnt/recovered.000 of=/mnt/resized.000 bs=6065
  526.  
  527.   Of course, it is possible that one or more of the blocks that made up
  528.   your file has been overwritten.  If so, then you're out of luck: that
  529.   block is gone forever.  (But just imagine if you'd unmounted sooner!)
  530.  
  531.   10.2.  Longer files
  532.  
  533.   The problems appear when the file has more than 12 data blocks.  It
  534.   pays here to know a little of how UNIX filesystems are structured.
  535.   The file's data is stored in units called `blocks'.  These blocks may
  536.   be numbered sequentially.  A file also has an `inode', which is the
  537.   place where information such as owner, permissions, and type are kept.
  538.   Like blocks, inodes are numbered sequentially, although they have a
  539.   different sequence.  A directory entry consists of the name of the
  540.   file and an inode number.
  541.  
  542.   But with this state of affairs, it is still impossible for the kernel
  543.   to find the data corresponding to a directory entry.  So the inode
  544.   also stores the location of the file's data blocks, as follows:
  545.  
  546.   ╖  The block numbers of the first 12 data blocks are stored directly
  547.      in the inode; these are sometimes referred to as the direct blocks.
  548.  
  549.   ╖  The inode contains the block number of an indirect block.  An
  550.      indirect block contains the block numbers of 256 additional data
  551.      blocks.
  552.  
  553.   ╖  The inode contains the block number of a doubly indirect block.  A
  554.      doubly indirect block contains the block numbers of 256 additional
  555.      indirect blocks.
  556.  
  557.   ╖  The inode contains the block number of a triply indirect block.  A
  558.      triply indirect block contains the block numbers of 256 additional
  559.      doubly indirect blocks.
  560.  
  561.   Read that again: I know it's complex, but it's also important.
  562.  
  563.   Now, the current kernel implementation (certainly for all versions up
  564.   to and including 2.0.30) unfortunately zeroes all indirect blocks (and
  565.   doubly indirect blocks, and so on) when deleting a file.  So if your
  566.   file was longer than 12 blocks, you have no guarantee of being able to
  567.   find even the numbers of all the blocks you need, let alone their
  568.   contents.
  569.  
  570.   The only method I have been able to find thus far is to assume that
  571.   the file was not fragmented: if it was, then you're in trouble.
  572.   Assuming that the file was not fragmented, there are several layouts
  573.   of data blocks, according to how many data blocks the file used:
  574.  
  575.      0 to 12
  576.         The block numbers are stored in the inode, as described above.
  577.  
  578.      13 to 268
  579.         After the direct blocks, count one for the indirect block, and
  580.         then there are 256 data blocks.
  581.  
  582.      269 to 65804
  583.         As before, there are 12 direct blocks, a (useless) indirect
  584.         block, and 256 blocks.  These are followed by one (useless)
  585.         doubly indirect block, and 256 repetitions of one (useless)
  586.         indirect block and 256 data blocks.
  587.  
  588.      65805 or more
  589.         The layout of the first 65804 blocks is as above.  Then follow
  590.         one (useless) triply indirect block and 256 repetitions of a
  591.         `doubly indirect sequence'.  Each doubly indirect sequence
  592.         consists of a (useless) doubly indirect block, followed by 256
  593.         repetitions of one (useless) indirect block and 256 data blocks.
  594.  
  595.   Of course, even if these assumed data block numbers are correct, there
  596.   is no guarantee that the data in them is intact.  In addition, the
  597.   longer the file was, the less chance there is that it was written to
  598.   the filesystem without appreciable fragmentation (except in special
  599.   circumstances).
  600.  
  601.   You should note that I assume throughout that your blocksize is 1024
  602.   bytes, as this is the standard value.  If your blocks are bigger, some
  603.   of the numbers above will change.  Specifically: since each block
  604.   number is 4 bytes long, blocksize/4 is the number of block numbers
  605.   that can be stored in each indirect block.  So every time the number
  606.   256 appears in the discussion above, replace it with blocksize/4.  The
  607.   `number of blocks required' boundaries will also have to be changed.
  608.  
  609.   Let's look at an example of recovering a longer file.
  610.  
  611.        debugfs:  stat <1387>
  612.        Inode: 148004   Type: regular    Mode:  0644   Flags: 0x0   Version: 1
  613.        User:   503   Group:   100   Size: 1851347
  614.        File ACL: 0    Directory ACL: 0
  615.        Links: 0   Blockcount: 3616
  616.        Fragment:  Address: 0    Number: 0    Size: 0
  617.        ctime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  618.        atime: 0x31a21dd1 -- Tue May 21 20:47:29 1996
  619.        mtime: 0x313bf4d7 -- Tue Mar  5 08:01:27 1996
  620.        dtime: 0x31a9a574 -- Mon May 27 13:52:04 1996
  621.        BLOCKS:
  622.        8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8583
  623.        TOTAL: 14
  624.  
  625.   There seems to be a reasonable chance that this file is not
  626.   fragmented: certainly, the first 12 blocks listed in the inode (which
  627.   are all data blocks) are contiguous.  So, we can start by retrieving
  628.   those blocks:
  629.  
  630.        # fsgrab -c 12 -s 8314 /dev/hda5 > /mnt/recovered.001
  631.  
  632.   Now, the next block listed in the inode, 8326, is an indirect block,
  633.   which we can ignore.  But we trust that it will be followed by 256
  634.   data blocks (numbers 8327 through 8582).
  635.  
  636.        # fsgrab -c 256 -s 8327 /dev/hda5 >> /mnt/recovered.001
  637.  
  638.   The final block listed in the inode is 8583.  Note that we're still
  639.   looking good in terms of the file being contiguous: the last data
  640.   block we wrote out was number 8582, which is 8327 + 255.  This block
  641.   8583 is a doubly indirect block, which we can ignore.  It is followed
  642.   by up to 256 repetitions of an indirect block (which is ignored)
  643.   followed by 256 data blocks.  So doing the arithmetic quickly, we
  644.   issue the following commands.  Notice that we skip the doubly indirect
  645.   block 8583, and the indirect block 8584 immediately (we hope)
  646.   following it, and start at block 8585 for data.
  647.  
  648.        # fsgrab -c 256 -s 8585 /dev/hda5 >> /mnt/recovered.001
  649.        # fsgrab -c 256 -s 8842 /dev/hda5 >> /mnt/recovered.001
  650.        # fsgrab -c 256 -s 9099 /dev/hda5 >> /mnt/recovered.001
  651.        # fsgrab -c 256 -s 9356 /dev/hda5 >> /mnt/recovered.001
  652.        # fsgrab -c 256 -s 9613 /dev/hda5 >> /mnt/recovered.001
  653.        # fsgrab -c 256 -s 9870 /dev/hda5 >> /mnt/recovered.001
  654.  
  655.   Adding up, we see that so far we've written 12 + (7 * 256) blocks,
  656.   which is 1804.  The `stat' results for the inode gave us a
  657.   `blockcount' of 3616; unfortunately these blocks are 512 bytes long
  658.   (as a hangover from UNIX), so we really want 3616/2 = 1808 blocks of
  659.   1024 bytes.  That means we need only four more blocks.  The last data
  660.   block written was number 10125.  As we've been doing so far, we skip
  661.   an indirect block (number 10126); we can then write those last four
  662.   blocks.
  663.  
  664.        # fsgrab -c 4 -s 10127 /dev/hda5 >> /mnt/recovered.001
  665.  
  666.   Now, with some luck the entire file has been recovered successfully.
  667.  
  668.   11.  Modifying inodes directly
  669.  
  670.   This method is, on the surface, much easier.  However, as mentioned
  671.   above, it cannot cope with files longer than 12 blocks.
  672.  
  673.   For each inode you want to recover, you must set the usage count to
  674.   one, and set the deletion time to zero.  This is done with the mi
  675.   (modify inode) command in debugfs.  Some sample output, modifying
  676.   inode 148003 from above:
  677.  
  678.   debugfs:  mi <148003>
  679.                             Mode    [0100644]
  680.                          User ID    [503]
  681.                         Group ID    [100]
  682.                             Size    [6065]
  683.                    Creation time    [833201524]
  684.                Modification time    [832708049]
  685.                      Access time    [826012887]
  686.                    Deletion time    [833201524] 0
  687.                       Link count    [0] 1
  688.                      Block count    [12]
  689.                       File flags    [0x0]
  690.                        Reserved1    [0]
  691.                         File acl    [0]
  692.                    Directory acl    [0]
  693.                 Fragment address    [0]
  694.                  Fragment number    [0]
  695.                    Fragment size    [0]
  696.                  Direct Block #0    [594810]
  697.                  Direct Block #1    [594811]
  698.                  Direct Block #2    [594814]
  699.                  Direct Block #3    [594815]
  700.                  Direct Block #4    [594816]
  701.                  Direct Block #5    [594817]
  702.                  Direct Block #6    [0]
  703.                  Direct Block #7    [0]
  704.                  Direct Block #8    [0]
  705.                  Direct Block #9    [0]
  706.                 Direct Block #10    [0]
  707.                 Direct Block #11    [0]
  708.                   Indirect Block    [0]
  709.            Double Indirect Block    [0]
  710.            Triple Indirect Block    [0]
  711.  
  712.   That is, I set the deletion time to 0 and the link count to 1 and just
  713.   pressed return for each of the other fields.  Granted, this is a
  714.   little unwieldy if you have a lot of files to recover, but I think you
  715.   can cope.  If you'd wanted chrome, you'd have used a graphical
  716.   `operating system' with a pretty `Recycle Bin'.
  717.  
  718.   By the way: the mi output refers to a `Creation time' field in the
  719.   inode.  This is a lie!  (Or misleading, anyway.)  The fact of the
  720.   matter is that you cannot tell on a UNIX filesystem when a file was
  721.   created.  The st_ctime member of a struct stat refers to the `inode
  722.   change time', that is, the last time when any inode details were
  723.   changed.  Here endeth today's lesson.
  724.  
  725.   Note that more recent versions of debugfs than the one I'm using
  726.   probably do not include some of the fields in the listing above
  727.   (specifically, Reserved1 and (some of?) the fragment fields).
  728.  
  729.   Once you've modified the inodes, you can quit debugfs and say:
  730.  
  731.        # e2fsck -f /dev/hda5
  732.  
  733.   The idea is that each of the deleted files has been literally
  734.   undeleted, but none of them appear in any directory entries.  The
  735.   e2fsck program can detect this, and will add a directory entry for
  736.   each file in the /lost+found directory of the filesystem.  (So if the
  737.   partition is normally mounted on /usr, the files will now appear in
  738.   /usr/lost+found.)  All that still remains to be done is to work out
  739.   the name of each file from its contents, and return it to its correct
  740.   place in the filesystem tree.
  741.  
  742.   When you run e2fsck, you will get some informative output, and some
  743.   questions about what damage to repair.  Answer `yes' to everything
  744.   that refers to `summary information' or to the inodes you've changed.
  745.   Anything else I leave up to you, although it's usually a good idea to
  746.   say `yes' to all the questions.  When e2fsck finishes, you can remount
  747.   the filesystem.
  748.  
  749.   Actually, there's an alternative to having e2fsck leave the files in
  750.   /lost+found: you can use debugfs to create a link in the filesystem to
  751.   the inode.  Use the link command in debugfs after you've modified the
  752.   inode:
  753.  
  754.        debugfs:  link <148003> foo.txt
  755.  
  756.   This creates a file called foo.txt in what debugfs thinks is the
  757.   current directory; foo.txt will be your file.  You'll still need to
  758.   run e2fsck to fix the summary information and block counts and so on.
  759.  
  760.   12.  Will this get easier in future?
  761.  
  762.   Yes.  In fact, I believe it already has.  Kernels in the development
  763.   2.1.x series have not zeroed indirect blocks since more than six
  764.   months ago.  At the beginning of December 1996, there was some talk on
  765.   the linux-kernel mailing-list of producing another 2.0.x production
  766.   kernel that also leaves indirect blocks intact on deletion.  Although
  767.   as of the pre-released versions of kernel 2.0.31 this has not
  768.   happened, I suspect that it is feasible.  Once Linus and the other
  769.   kernel hackers overcome this limitation in the production kernels, a
  770.   lot of my objections to the technique of modifying inodes by hand will
  771.   disappear.  At the very latest, this should happen on the release of
  772.   the 2.2.x kernel series, which (according to historical kernel
  773.   development time-scales) should happen some time in the first quarter
  774.   of 1998.  When this wart is corrected, it will also be possible to use
  775.   the dump command in debugfs on long files.
  776.  
  777.   13.  Are there any tools to automate this process?
  778.  
  779.   As it happens, there are.  Unfortunately, I believe that they suffer
  780.   from the same problem as the manual inode modification technique:
  781.   indirect blocks are unrecoverable.  However, given the likelihood that
  782.   this will shortly no longer be a problem, it's well worth looking
  783.   these programs out now.
  784.  
  785.   Someone on the net mentioned lde by Scott Heavner.  To be honest, I
  786.   wouldn't recommend this as a tool for automating file recovery.  It's
  787.   more like a full-screen debugfs than anything else, although it does
  788.   have some features like the ability to scan for certain types of file
  789.   or for certain file contents.  It also works with the xia (does anyone
  790.   actually use this any more?)  and minix filesystems, which I guess is
  791.   its major selling point these days.  Version 2.3.4 is available on
  792.   Sunsite
  793.   <ftp://sunsite.unc.edu/pub/Linux/system/Filesystems/lde-2.3.4.tar.gz>
  794.   and mirrors (although it's possible there's a more recent version than
  795.   this; I found that one on an 8-month-old CD-ROM archive).  lde does
  796.   have some fairly useful documentation on basic filesystem concepts, as
  797.   well as a document on how to use it for recovering deleted files.
  798.   Although I haven't used it, I suspect that my method above is better.
  799.  
  800.   It sounds like the program that really works is the GNU Midnight
  801.   Commander, mc.  This is a full-screen file management tool, based
  802.   AFAIK on a certain MS-DOS program commonly known as `NC'.  mc supports
  803.   the mouse on the Linux console and in an xterm, and provides virtual
  804.   filesystems which allow tricks like cd-ing to a tarfile.  Among its
  805.   virtual filesystems is one for ext2 undeletion.  It all sounds very
  806.   handy, although I must admit I've never used the program myself -- I
  807.   prefer good old-fashioned shell commands.  Apparently one must
  808.   configure the program with the --with-ext2undel option; you'll also
  809.   need the development libraries and include files that come with the
  810.   e2fsprogs package.  I gather that once the program is built, you can
  811.   tell it to cd undel:dev/hda5/, and get a `directory listing' of
  812.   deleted files.
  813.  
  814.   The latest non-development version is probably 4.0; as with the kernel
  815.   itself, development versions are not recommended to non-hackers.  The
  816.   list of (over 70) download sites is available on the Midnight
  817.   Commander 4 website <http://mc.blackdown.org/mc4/>, or try the
  818.   official ftp site
  819.   <ftp://ftp.nuclecu.unam.mx/linux/local/mc-4.0.tar.gz> (which if memory
  820.   serves is rather slow).
  821.  
  822.   14.  Colophon
  823.  
  824.   I intend to produce regular updates to this document as long as I have
  825.   both enough time to do it, and something interesting to say.  This
  826.   means that I am eager to hear comments from readers.  Could my writing
  827.   be clearer?.  Can you think of something that would make matters
  828.   easier?  Is there some new tool that does it all automatically?  Who
  829.   did kill JFK?
  830.  
  831.   Whatever.  If you have something to say, about this document or any
  832.   other subject, drop me a line on <aaronc@pobox.com>.
  833.  
  834.   15.  Credits and Bibliography
  835.  
  836.        `If I have seen farther than others, it is because I was
  837.        standing on the shoulders of giants.' (Isaac Newton)
  838.  
  839.   Much of this mini-Howto was derived from a posting in the
  840.   comp.os.linux.misc newsgroup by Robin Glover <swrglovr@met.rdg.ac.uk>.
  841.   I would like to thank Robin for graciously allowing me to rework his
  842.   ideas into this mini-Howto.
  843.  
  844.   Some bibliographic references:
  845.  
  846.   ╖  Frisch, ╞leen (1995), Essential System Administration, second
  847.      edition, O'Reilly and Associates, Inc., ISBN: 1-56592-127-5.
  848.  
  849.   ╖  Glover, Robin (31 Jan 1996), HOW-TO : undelete linux files
  850.      (ext2fs/debugfs), comp.os.linux.misc Usenet posting.
  851.  
  852.   ╖  Peek, Jerry, Tim O'Reilly, Mike Loukides et al (1993), UNIX Power
  853.      Tools, O'Reilly and Associates, Inc./Random House, Inc., ISBN:
  854.      0-679-79073-X.
  855.  
  856.   16.  Legalities
  857.  
  858.   All trademarks are the property of their respective owners.
  859.   Specifically:
  860.  
  861.   ╖  MS-DOS and Windows are trademarks of Microsoft
  862.      <http://www.microsoft.com/>.
  863.  
  864.   ╖  UNIX is a trademark of the Open Group <http://www.open.org/>.
  865.  
  866.   ╖  The trademark status of the name Linux is currently being contested
  867.      by lawyers.  A certain Walter R. Della Croce has made an allegedly
  868.      false trademark registration for the term.  Further information on
  869.      the Linux trademark issue is available from the Linux Mall
  870.      <http://www.linuxmall.com/announce/>.
  871.  
  872.   This document is Copyright ⌐ 1997 Aaron Crane <aaronc@pobox.com>.  It
  873.   may be freely redistributed in its entirety, including the whole of
  874.   this copyright notice, but may not be changed without permission from
  875.   either the author or the Linux Documentation Project Coordinator.
  876.   Dispensation is granted for copying small verbatim portions for the
  877.   purposes of reviews or for quoting; in these circumstances, sections
  878.   may be reproduced in the presence of an appropriate citation but
  879.   without this copyright notice.
  880.  
  881.   The author requests but does not require that parties intending to
  882.   sell copies of this document, whether on computer-readable or human-
  883.   readable media, inform either him or the Linux HOWTO Coordinator of
  884.   their intentions.
  885.  
  886.   The Linux HOWTO Coordinator is Greg Hankins <gregh@sunsite.unc.edu>.
  887.  
  888.